//
//  BN_NoticeViewCtrlData.m
//  BabyNow
//
//  Created by 刘泽琛 on 14-5-13.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#import "BN_NoticeViewCtrlData.h"

@implementation BN_NoticeViewCtrlData {
    NSArray *files_;
    NSInteger replTime_;
    NSIndexPath *currentIndexPath;

}

- (id)init {
    if (self = [super init]) {
        
        if (!self.noticeHelper) {
            self.noticeHelper = [[BN_NoticeHelper alloc]init];
        }
        
        if (!self.netArray) {
            self.netArray = [[NSMutableArray alloc]init];
        }        
        
        // 数据请求
        [self performSelectorInBackground:@selector(loadNetData) withObject:nil];
        
        // 刷新列表
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshListData) name:KREFRESH_NOTICELIST object:nil];
        }
    return self;
}

- (void)refreshListData {
    if (!self.noticeHelper) {
        self.noticeHelper = [[BN_NoticeHelper alloc]init];
    }
    [self loadNetData];
}

#pragma mark
#pragma mark 列表委托和数据源

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.netArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"BN_NoticeCell";
    BN_NoticeCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"BN_NoticeCell" owner:nil options:nil]objectAtIndex:0];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    
    for (UIView *view in cell.displayImageView.subviews) {
        [view removeFromSuperview];
    }
    for (UIView *view in cell.replView.subviews) {
        [view removeFromSuperview];
    }
    
    cell.cellTag = indexPath.row;
    
    // 权限
    // notiUserType
    NSInteger notiUserType = [self.netArray[indexPath.row][@"notiUserType"] integerValue];
    [self noticeUserType:cell.deleteDynamicBtn userType:notiUserType];
    
    // 是否收藏
    cell.favoFlg = [self.netArray[indexPath.row][@"favoFlg"] integerValue];
    
    cell.infoArray = self.netArray;
    
    cell.notiId = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"notiId"]];
    
    cell.userName.text = self.netArray[indexPath.row][@"notiUserName"];
    
    NSString *dateStr = self.netArray[indexPath.row][@"notiDate"];
    NSRange rang = NSMakeRange(10, 6);
    NSString * strRang = [dateStr substringWithRange:rang];
    cell.sendTime.text = strRang;
    
    // 赞
    cell.praiFlg = [self.netArray[indexPath.row][@"praiFlg"]intValue];
    cell.praiTime = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"praiTime"]];
    NSString *praiTime = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"praiTime"]];
    cell.likeLabel.backgroundColor = [UIColor clearColor];
    cell.likeLabel.text = praiTime;
    [cell dealLikeBtnColorState];
    
    // 浏览次数 browTime
    NSString *browTime = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"browTime"]];
    if (![browTime isEqual:[NSNull null]]) {
        
        cell.lookTimes.text = [NSString stringWithFormat:@"浏览%@次",browTime];
    }else {
        cell.lookTimes.text = @"浏览0次";
    }
    
    // 评论数量 replTime 居然是数值型....
    cell.replTime = [self.netArray[indexPath.row][@"replTime"] integerValue];
    NSString *replTime = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"replTime"]];
    if (![replTime isEqual:[NSNull null]]) {
        for (UILabel *view in cell.pingLunBtn.subviews) {
            if ([view isKindOfClass:[UILabel class]]) {
                [view removeFromSuperview];
            }
        }
        UILabel *pinlunLabel = [[UILabel alloc]init];
        
        switch (MAIN_VERSION) {
            case 7:
                pinlunLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+1, 50, 12);
                break;
            case 6:
                pinlunLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+2, 50, 12);
                break;
            default:
                break;
        }
        
        pinlunLabel.backgroundColor = [UIColor clearColor];
        UIColor *color = APP_OBJECT_GREEN_COLOR;
        pinlunLabel.textColor = color;
        pinlunLabel.font = [UIFont systemFontOfSize:12];
        pinlunLabel.text = replTime;
        [cell.pingLunBtn addSubview:pinlunLabel];
    }
    
    // fileFlg为0是图片
    NSArray *files = self.netArray[indexPath.row][@"files"];
    [cell imgArray:files];
    
    // 文字内容
    NSString *postSubj = self.netArray[indexPath.row][@"notiSubj"];
    if (![postSubj isEqual:[NSNull null]]) {
        if (![postSubj isEqualToString:@"  写点什么呢..."]) {
            cell.contentText.text = postSubj;
        }
    }
    [cell.contentText sizeToFit];
    [cell relayout];
    // 评论数
    cell.replArr = self.netArray[indexPath.row][@"repls"];
    return cell;
}

#pragma mark 
#pragma mark 网络数据
- (void)loadNetData {
    __block BN_NoticeViewCtrlData *blockSelf_ = self;
    self.noticeHelper.queryNoticeListHandler = ^(id result,NSString *errorMsg){
        // update by jason yan 2014-05-30
        if (errorMsg) {
            [[NSNotificationCenter defaultCenter]postNotificationName:KNOTICE_HINTMESSAGE object:errorMsg];
            blockSelf_.listReload(YES);
        }
        if(result){
            [blockSelf_ reloadTableViewInfo:result];
        }
    };
    [self.noticeHelper refreshNoticeList];
}

- (void)reloadTableViewInfo:(NSMutableArray *)info {
    self.netArray = info;
    self.listReload(YES);
}

/**
 *  计算cell高度
 */
- (float)calcCellHeight:(NSIndexPath *)indexPath {

    float height = 0.0;
    
    // notiSubj 高度
    NSString *notiSubj = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"notiSubj"]];
    UIFont * contLabelfont = [UIFont systemFontOfSize:APP_CONTENT_FONT_SIZE];
    CGSize contLabelsize = CGSizeMake(296,10000);
    NSDictionary * contLabeldic = [NSDictionary dictionaryWithObjectsAndKeys:contLabelfont,NSFontAttributeName,nil];
    CGSize contLabelActualsize = [self getTextSize:contLabelsize disFont:contLabelfont contentStr:notiSubj contextDic:contLabeldic];
    
    files_ = self.netArray[indexPath.row][@"files"];
    replTime_ = [self.netArray[indexPath.row][@"replTime"]integerValue];
    
    // 评论View高度
    NSInteger replCount = 0;
    if (replTime_ >= 3) {
        replCount = 3*15+10;
    }
    if (replTime_ == 2) {
        replCount = 2*15+5;
    }
    if (replTime_ == 1) {
        replCount = 15;
    }
    if (replTime_ == 0) {
        replCount = -15;
    }
    
    // 如果有图片的话
    if (files_.count > 0) {
        height = 475+(replCount+contLabelActualsize.height-15);
    }else {
        if (contLabelActualsize.height < 17) {
            height = 475+replCount-SCREEN_WIDTH-10;
        }else {
            height = 475+replCount-SCREEN_WIDTH-15+(contLabelActualsize.height-10);
        }
    }
    
    NSLog(@"%f",height);

    return height;
}

// 封装自动撑开高度的方法
- (CGSize)getTextSize:(CGSize)provisionsSize disFont:(UIFont *)font contentStr:(NSString *)contentStr contextDic:(NSDictionary *)contextDic {
    
    CGSize size;
    switch (MAIN_VERSION) {
        case 7:
            size =[contentStr boundingRectWithSize:provisionsSize options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:contextDic context:nil].size;
            
            break;
            
        case 6:
            size = [contentStr sizeWithFont:font constrainedToSize:provisionsSize lineBreakMode:UILineBreakModeWordWrap];
            break;
        default:
            break;
    }
    return size;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return [self calcCellHeight:indexPath];
}

#pragma mark - 刷新控件的代理方法
- (void)upLoadFinished:(MJRefreshBaseView *)refreshView {
    // 列表开始加载，开始数据请求
    // [self loadNextNetData];
    
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 列表开始刷新，开始数据请求
    [self loadNetData];
    
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    switch ([refreshView viewType]) {
        case -1:
            [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:0.85];
            break;
        case 1:
            [self performSelector:@selector(upLoadFinished:) withObject:refreshView afterDelay:0];
            break;
        default:
            break;
    }
}

- (void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{
}

- (void)refreshView:(MJRefreshBaseView *)refreshView stateChange:(MJRefreshState)state
{
    switch (state) {
        case MJRefreshStateNormal:
            break;
            
        case MJRefreshStatePulling:
            break;
            
        case MJRefreshStateRefreshing:
            break;
        default:
            break;
    }
}

#pragma mark ScrollView
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
}

#pragma mark
#pragma mark 生命周期
- (void)dealloc
{
    NSLog(@"通知Modal释放...");
}
@end
